package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.MaterialMapper;
import com.heima.wemedia.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-11 15:29
 */
@Service
@Slf4j
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, WmMaterial> implements MaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    @Transactional(rollbackFor = Exception.class) //默认回滚只针对runtimeException 对于IO异常之类不会回滚
    public WmMaterial upload(MultipartFile multipartFile) {

        WmUser user = WmThreadLocalUtil.getUser();
        if(user == null){
            //用户信息有问题
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        String path = null;
        try{
            String uuid = UUID.randomUUID().toString();
            String originalFilename = multipartFile.getOriginalFilename(); //a.jpg
            int i = originalFilename.lastIndexOf(".");
            if(i > 0){
                String substring = originalFilename.substring(i);
                uuid = uuid + substring;
            }

            //1.上传到minio
            path =
                    fileStorageService.uploadImgFile(null, uuid , multipartFile.getInputStream());

            //2.写入数据库
            WmMaterial material = new WmMaterial();
            material.setCreatedTime(new Date());
            material.setUrl(path);
//            material.setType((short)0);
//            material.setIsCollection((short)0);
            material.setUserId(user.getId());

            save(material);
            //额外代码

            return material;
        }catch (Exception e){
            if(StringUtils.isNotBlank(path)){
                //写入了minio
                fileStorageService.delete(path);
            }

            log.error("上传文件失败",e);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
